package cn.kgc.redis.config;

import cn.hutool.json.JSONUtil;
import org.apache.ibatis.cache.Cache;
import org.springframework.data.redis.core.StringRedisTemplate;

/**
 * @author 课工场
 * @date 2024/5/31
 * @description
 */
public class RedisCache implements Cache {

    //  命名空间
    private final String id;

    // String id  命名空间
    public RedisCache(String id){
        System.out.println("id = " + id);
        this.id = id;
    }
    @Override
    public String getId() {
        return this.id;
    }


    // 缓存数据
    @Override
    public void putObject(Object key, Object value) {
        System.out.println("----------redis开始缓存数据-----------");
        //   redis中  hash
        StringRedisTemplate stringRedisTemplate = stringRedisTemplate();
        stringRedisTemplate.opsForHash().put(id,key.toString(), JSONUtil.toJsonStr(value));
    }


    // 获取缓存
    @Override
    public Object getObject(Object key) {
        System.out.println("----------从redis获取缓存数据-----------");
        StringRedisTemplate stringRedisTemplate = stringRedisTemplate();
        Object o = JSONUtil.parse(stringRedisTemplate.opsForHash().get(id, key.toString()));
        return o;
    }

    @Override
    public Object removeObject(Object key) {
        return null;
    }


    // 清空缓存
    @Override
    public void clear() {
        System.out.println("----------清空redis缓存数据-----------");
        StringRedisTemplate stringRedisTemplate = stringRedisTemplate();
        stringRedisTemplate.delete(id);
    }

    @Override
    public int getSize() {
        return 0;
    }

    public StringRedisTemplate   stringRedisTemplate(){
        StringRedisTemplate stringRedisTemplate = (StringRedisTemplate) ApplicationContextUtil.getBean("stringRedisTemplate");
        return stringRedisTemplate;
    }

}
